{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2023 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# chemical_balance_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/chemical_balance_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/chemical_balance_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "We are trying to group items in equal sized groups.\n",
    "\n",
    "Each item has a color and a value. We want the sum of values of each group to be\n",
    "as close to the average as possible. Furthermore, if one color is an a group, at\n",
    "least k items with this color must be in that group.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "from typing import Sequence\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "def chemical_balance():\n",
    "    \"\"\"Solves the chemical balance problem.\"\"\"\n",
    "    # Data\n",
    "    max_quantities = [\n",
    "        [\"N_Total\", 1944],\n",
    "        [\"P2O5\", 1166.4],\n",
    "        [\"K2O\", 1822.5],\n",
    "        [\"CaO\", 1458],\n",
    "        [\"MgO\", 486],\n",
    "        [\"Fe\", 9.7],\n",
    "        [\"B\", 2.4],\n",
    "    ]\n",
    "\n",
    "    chemical_set = [\n",
    "        [\"A\", 0, 0, 510, 540, 0, 0, 0],\n",
    "        [\"B\", 110, 0, 0, 0, 160, 0, 0],\n",
    "        [\"C\", 61, 149, 384, 0, 30, 1, 0.2],\n",
    "        [\"D\", 148, 70, 245, 0, 15, 1, 0.2],\n",
    "        [\"E\", 160, 158, 161, 0, 10, 1, 0.2],\n",
    "    ]\n",
    "\n",
    "    num_products = len(max_quantities)\n",
    "    all_products = range(num_products)\n",
    "\n",
    "    num_sets = len(chemical_set)\n",
    "    all_sets = range(num_sets)\n",
    "\n",
    "    # Model\n",
    "\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    # Scale quantities by 100.\n",
    "    max_set = [\n",
    "        int(\n",
    "            math.ceil(\n",
    "                min(\n",
    "                    max_quantities[q][1] * 1000 / chemical_set[s][q + 1]\n",
    "                    for q in all_products\n",
    "                    if chemical_set[s][q + 1] != 0\n",
    "                )\n",
    "            )\n",
    "        )\n",
    "        for s in all_sets\n",
    "    ]\n",
    "\n",
    "    set_vars = [model.NewIntVar(0, max_set[s], f\"set_{s}\") for s in all_sets]\n",
    "\n",
    "    epsilon = model.NewIntVar(0, 10000000, \"epsilon\")\n",
    "\n",
    "    for p in all_products:\n",
    "        model.Add(\n",
    "            sum(int(chemical_set[s][p + 1] * 10) * set_vars[s] for s in all_sets)\n",
    "            <= int(max_quantities[p][1] * 10000)\n",
    "        )\n",
    "        model.Add(\n",
    "            sum(int(chemical_set[s][p + 1] * 10) * set_vars[s] for s in all_sets)\n",
    "            >= int(max_quantities[p][1] * 10000) - epsilon\n",
    "        )\n",
    "\n",
    "    model.Minimize(epsilon)\n",
    "\n",
    "    # Creates a solver and solves.\n",
    "    solver = cp_model.CpSolver()\n",
    "    status = solver.Solve(model)\n",
    "    print(f\"Status = {solver.StatusName(status)}\")\n",
    "    # The objective value of the solution.\n",
    "    print(f\"Optimal objective value = {solver.ObjectiveValue() / 10000.0}\")\n",
    "\n",
    "    for s in all_sets:\n",
    "        print(f\"  {chemical_set[s][0]} = {solver.Value(set_vars[s]) / 1000.0}\", end=\" \")\n",
    "        print()\n",
    "    for p in all_products:\n",
    "        name = max_quantities[p][0]\n",
    "        max_quantity = max_quantities[p][1]\n",
    "        quantity = sum(\n",
    "            solver.Value(set_vars[s]) / 1000.0 * chemical_set[s][p + 1]\n",
    "            for s in all_sets\n",
    "        )\n",
    "        print(f\"{name}: {quantity} out of {max_quantity}\")\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "    chemical_balance()\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
